package wox.lonice.service.leguan.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import wox.lonice.common.BaseConstant;
import wox.lonice.dto.leguan.*;
import wox.lonice.service.leguan.LeguanHotService;
import wox.lonice.utis.BeanUtil;
import wox.lonice.utis.HttpsUtils;
import wox.lonice.utis.MailUtil;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class LeguanHotServiceImpl implements LeguanHotService {
    private final static Logger logger = LoggerFactory.getLogger(LeguanHotService.class);

    private String[] titleKeyword = {"脱单", "官宣", "病毒", "猫", "狗"};

    //"0 0 12 * * ?"    每天中午十二点触发
    //"0 15 10 ? * *"    每天早上10：15触发
    //"0 15 10 * * ?"    每天早上10：15触发
    //"0 15 10 * * ? *"    每天早上10：15触发
    //"0 15 10 * * ? 2005"    2005年的每天早上10：15触发
    //"0 * 14 * * ?"    每天从下午2点开始到2点59分每分钟一次触发
    //"0 0/5 14 * * ?"    每天从下午2点开始到2：55分结束每5分钟一次触发
    //"0 0/5 14,18 * * ?"    每天的下午2点至2：55和6点至6点55分两个时间段内每5分钟一次触发
    //"0 0-5 14 * * ?"    每天14:00至14:05每分钟一次触发
    //"0 10,44 14 ? 3 WED"    三月的每周三的14：10和14：44触发
    //"0 15 10 ? * MON-FRI"    每个周一、周二、周三、周四、周五的10：15触发
    @Scheduled(cron="0 0 8,11,18 * * ? ")   //早上8点，中午11点，下午6点
    @Override
    public List<HotDataRow> getHot() {
        List<HotDataRow> hotDataRowBaiduList = Lists.newArrayList();
        hotDataRowBaiduList.addAll(Objects.requireNonNull(this.getHotsPot(0, 1)));
        hotDataRowBaiduList.addAll(Objects.requireNonNull(this.getHotsPot(0, 2)));
        hotDataRowBaiduList.addAll(Objects.requireNonNull(this.getHotsPot(0, 5)));
        hotDataRowBaiduList = this.screenHot(hotDataRowBaiduList);

        List<HotDataRow> hotDataRowOtherList = Lists.newArrayList();
        //1-1  0-1,0-2,0-5
        hotDataRowOtherList.addAll(Objects.requireNonNull(this.getHotsPot(1, 1)));
        //领域
        hotDataRowOtherList.addAll(Objects.requireNonNull(this.getHotText("", "")));
        hotDataRowOtherList = this.screenHot(hotDataRowOtherList);

        List<HotDataRow> hotDataRowList = Lists.newArrayList();
        hotDataRowList.addAll(hotDataRowBaiduList);
        hotDataRowList.addAll(hotDataRowOtherList);

        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        StringBuffer body = new StringBuffer();
        hotDataRowList.forEach(hotDataRow -> body.append("<a href=\"" + hotDataRow.getUrl() + "\">[ <" + hotDataRow.getPlatform() + ">" + hotDataRow.getTitle() + " ]</a><br/>"));
        MailUtil.sendHtmlMail("wox666@sina.com", df.format(LocalDateTime.now()) + " : 实时热点新闻 - " + hotDataRowList.size() + " 条", body.toString());
//        MailUtil.sendHtmlMail("2281771977@qq.com", df.format(LocalDateTime.now()) + " : 实时热点新闻 - " + hotDataRowList.size() + " 条", body.toString());
        return hotDataRowList;
    }

    /**
     * lhwType  1:微博热搜
     * lhwColumnId 1:热榜搜 2:新时代
     * <p>
     * lhwType  0:百度热搜
     * lhwColumnId 1:实时热点 2:今日热点  3:七日热点  4:民生热点  5:娱乐热点  6:体育热点
     *
     * @param lhwType
     * @param lhwColumnId
     */
    private List<HotDataRow> getHotsPot(Integer lhwType, Integer lhwColumnId) {
        LocalDateTime localDateTime = LocalDateTime.now();//当前时间
        LocalDateTime beginTimeLong = localDateTime.minusHours(1);//小一个小时
        HotSpotRequest hostPotRequest = new HotSpotRequest()
                .setLhwStatus(1).setLhwType(lhwType).setLhwColumnId(lhwColumnId)
                .setPageSize(30).setBeginTimeLong(beginTimeLong.toInstant(ZoneOffset.of("+8")).toEpochMilli())
                .setLgCustomerId(1000962950).setReqTime(localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli());
        Map<String, String> map = BeanUtil.beanToMap(hostPotRequest);
        String result = null;
        try {
            result = HttpsUtils.send(BaseConstant.LEGUAN_HOTSPOT, map, HttpsUtils.METHOD_ENCODING_UTF8);
        } catch (KeyManagementException | NoSuchAlgorithmException | IOException e) {
            e.printStackTrace();
        }
        //返回的数据转化bean
        JSONObject jsonObject = new JSONObject(result);
        HotResponse hotResponse = jsonObject.toBean(HotResponse.class);
        if (ObjectUtil.isNull(hotResponse.getReObj())) {
            return null;
        }
        return this.dealHotsPotObject(hotResponse.getReObj());
    }

    /**
     * @param platform 平台
     * @param domain   领域
     */
    private List<HotDataRow> getHotText(String platform, String domain) {
        LocalDateTime localDateTime = LocalDateTime.now();//当前时间
        LocalDateTime lptime = localDateTime.minusHours(12);//小30个小时
        HotTextRequest hotTextRequest = new HotTextRequest()
                .setTitle("")
                .setPlatform(platform)
                .setDomain(domain)
                .setLptime(lptime.toEpochSecond(ZoneOffset.of("+8")))
                .setReadOrder(BaseConstant.DESC)
                .setRead(0)
                .setStatus(1)
                .setPage(1)
                .setSize(200)
                .setLgCustomerId(1000962950)
                .setReqTime(localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli());
        Map<String, String> map = BeanUtil.beanToMap(hotTextRequest);
        Map<String, String> requestMap = new HashMap<>();
        map.forEach((key, value) -> {
            if (!"null".equals(value) && !"".equals(value)) {
                requestMap.put(key, value);
            }
        });
        String result = null;
        try {
            result = HttpsUtils.send(BaseConstant.LEGUAN_HOTTEXT, requestMap, HttpsUtils.METHOD_ENCODING_UTF8);
        } catch (KeyManagementException | NoSuchAlgorithmException | IOException e) {
            e.printStackTrace();
        }
        //返回的数据转化bean
        JSONObject jsonObject = new JSONObject(result);
        HotResponse hotResponse = jsonObject.toBean(HotResponse.class);
        if (ObjectUtil.isNull(hotResponse.getReObj())) {
            return null;
        }
        return this.dealHotTextObject(hotResponse.getReObj());
    }

    private List<HotDataRow> dealHotsPotObject(Object object) {
        List<HotDataRow> hotDataRowList = Lists.newArrayList();
        if (object instanceof ArrayList) {
            JSONArray jsonArray = new JSONArray(object);
            HotSpot[] hotSpots = (HotSpot[]) jsonArray.toArray(HotSpot.class);
            Lists.newArrayList(hotSpots)
                    .forEach(hotSpot -> hotDataRowList.add(new HotDataRow()
                            .setTitle(hotSpot.getLhwWord()).setUrl(hotSpot.getLhwUrl())
                            .setRead(hotSpot.getLhwHot())
                            .setTarget(hotSpot.getLhmTarget())
                            .setPlatform(hotSpot.getLhwType() == 0 ? "百度热搜" : "微博热搜")));
        }
        return hotDataRowList;
    }

    private List<HotDataRow> dealHotTextObject(Object object) {
        List<HotDataRow> hotDataRowList = Lists.newArrayList();
        JSONObject jsonObject = new JSONObject(object);
        JSONArray jsonArray = jsonObject.getJSONArray("content");
        HotText[] hotTexts = (HotText[]) jsonArray.toArray(HotText.class);
        Lists.newArrayList(hotTexts).stream()
                .filter(hotText -> 1 == hotText.getMediaType())//只要图文的
                .forEach(hotText -> hotDataRowList.add(new HotDataRow()
                        .setTitle(hotText.getTitle()).setUrl(hotText.getUrl())
                        .setRead(hotText.getRead())
                        .setPlatform(hotText.getPlatform())));
        return hotDataRowList;
    }

    /**
     * 做筛选
     *
     * @param hotDataRowList
     * @return
     */
    private List<HotDataRow> screenHot(List<HotDataRow> hotDataRowList) {
        //获取前十的数量
        Set<HotDataRow> hotDataRowSet = hotDataRowList.stream()
                .sorted(Comparator.comparing(HotDataRow::getRead).reversed())
                .limit(10).collect(Collectors.toSet());
        hotDataRowList.stream()
                .filter(hotDataRow -> "热".equals(hotDataRow.getTarget()) ||
                        ("新".equals(hotDataRow.getTarget()) && !"百度热搜".equals(hotDataRow.getPlatform())) ||
                        Lists.newArrayList(titleKeyword).stream()
                                .anyMatch(str -> hotDataRow.getTitle().contains(str)))
                .forEach(hotDataRowSet::add);
        return Lists.newArrayList(hotDataRowSet);
    }


    public static void main(String[] args) {
//        new LeguanHostServiceImpl().getHotsPot(1, 1);
//        new LeguanHostServiceImpl().getHotText("", "");

//        startIssue=&endIssue=&sIssue=&eIssue=&maxsize=10&openDate=&statisticsTag=1&sortTag=up
//        Map<String, String> map = Maps.newHashMap();
//        map.put("maxsize", "10");
//        map.put("statisticsTag", "1");
//        map.put("sortTag", "up");
//
//        String result = null;
//        try {
//            result = HttpsUtils.send("http://zst.aicai.com/dlt/", map, HttpsUtils.METHOD_ENCODING_UTF8);
//        } catch (KeyManagementException | NoSuchAlgorithmException | IOException e) {
//            e.printStackTrace();
//        }
//        System.out.println(result);

//        new LeguanHotServiceImpl().getHot();

        List<HotDataRow> hotDataRows = Lists.newArrayList();
        hotDataRows.add(new HotDataRow().setTitle("111").setRead(1).setPlatform("11"));
        hotDataRows.add(new HotDataRow().setTitle("222").setRead(2).setPlatform("22"));
        hotDataRows.add(new HotDataRow().setTitle("333").setRead(3).setPlatform("33"));
        hotDataRows.add(new HotDataRow().setTitle("444").setRead(4).setPlatform("44"));

//        LinkedList<HotDataRow> linkedList = Lists.newLinkedList(hotDataRows);
        LinkedList<HotDataRow> linkedList = new LinkedList<>(hotDataRows);

//        System.out.println(com.alibaba.fastjson.JSONObject.toJSONString(linkedList));

//        Stream.iterate(0, rowNum -> rowNum + 1).limit(hotDataRows.size())
//        .forEach(hotDataRow -> {
////            if(!linkedList.isEmpty()){
//                System.out.println(hotDataRow);
////            }
//
//        });
        hotDataRows.forEach(hotDataRow -> {
//            if(!linkedList.isEmpty()){
            System.out.println(hotDataRow);
//            }

        });

        for(int i = 0; i<hotDataRows.size(); i++){
            HotDataRow addOrderPackage = hotDataRows.get(i);
            addOrderPackage.setTitle(addOrderPackage.getPlatform() + "-" + (i + 1));
        }
        hotDataRows.forEach(hotDataRow -> {
//            if(!linkedList.isEmpty()){
            System.out.println(hotDataRow);
//            }

        });

//        if(linkedList.isEmpty()){
//            linkedList.clear();
//        }

        System.out.println(linkedList.poll());



    }
}
